"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by siyi.chen on '16/01/2025'
    comment: mqtt推送消息
"""
import asyncio
from project.middleware.mqtt import AsyncMQTT


class MQTTService:

    @staticmethod
    async def push(topic, message, qos=2):
        """
        推送消息
        :param topic: 主题
        :param message: 消息内容 string、bytearray、int、float 或 None
        :param qos: 消息等级，默认2 (0:最多一次，1:至少一次，2:仅一次)
        """
        async_mqtt = AsyncMQTT()
        try:
            await async_mqtt.connect()
            await async_mqtt.publish(topic, message, qos)
        finally:
            await async_mqtt.disconnect()

    @staticmethod
    async def subscribe(topic, qos=2):
        """
        订阅消息
        :param topic: 主题
        :param qos: 消息等级，默认2 (0:最多一次，1:至少一次，2:仅一次)
        """
        async_mqtt = AsyncMQTT()
        try:
            await async_mqtt.connect()
            await async_mqtt.subscribe(topic, qos)
        finally:
            # 在实际应用中，可能不希望立即断开连接，因为还需要接收消息
            # await async_mqtt.disconnect()
            pass


if __name__ == "__main__":

    asyncio.run(MQTTService.push("flow_list","123455"))
    # asyncio.run(MQTTService.subscribe("test/topic"))

